import React from 'react'
import {connect} from 'react-redux'
import BasicInfo from 'components/basic-info';
import {messages} from 'share/common';
import { Button, message, Affix, Popover } from 'antd';
import ResizeTable from 'components/resize-table'
import SlideFrame from 'components/slide-frame';
import menuRoute from 'routes/menuRoute'
import 'styles/setting/wait-for-billing/invoice-status-query.scss';
import MappingRule from 'containers/financial-account/interface-definition/mapping-rule';
import interfaceService from "containers/financial-account/interface-definition/interface-service";

class mappingSetting extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      infoList: [
        {type: 'input', id: 'elementCode', label: messages('financial-account.key83')/*核算要素编码*/},
        {type: 'input', id: 'elementName', label: messages('financial-account.key84')/*核算要素名称*/},
      ],
      infoData: {},
      columns: [
        {title: messages('financial-account.key100')/*核算业务定义编码*/,dataIndex: 'functionDefineCode'},
        {title: messages('financial-account.key101')/*核算业务定义名称*/,dataIndex: 'functionDefineName'},
        {title: messages('financial-account.key63')/*来源数据编码*/,dataIndex: 'detailSourceCode'},
        {title: messages('financial-account.key64')/*来源数据名称*/,dataIndex: 'detailSourceName'},
        { title: messages('financial-account.key65')/*映射字段编码*/,dataIndex: 'segmentCode',
          render: (value, record) => {
            let res = `${record.parentSegmentCode ? record.parentSegmentCode + '-' : ''}${value}`;
            return <Popover content={res}>{res}</Popover>
          } },
        { title: messages('financial-account.key66')/*映射字段名称*/,dataIndex: 'segmentName',
          render: (value, record) => {
            let res = `${record.parentSegmentName ? record.parentSegmentName + '-' : ''}${value}`;
            return <Popover content={res}>{res}</Popover>
          } },
        {title: messages('financial-account.key5')/*是否预置*/,dataIndex: 'isDefault', width: 96, render: (value) => value ? messages('components.key378')/*是*/ : messages('components.key377')/*否*/},
        {title: messages('common.operation')/*操作*/,dataIndex: 'operation', width: 72, render: (value,record) => {
            const { deleting } = this.state;
            return <span>
              {record.isDefault ? '-' : <a onClick={deleting ? null : e => this.handleDelete(e,record)} style={{color: deleting ? '#cccccc' : '#4B8DFF'}}>{messages('common.delete')/*删除*/}</a>}
            </span>;}}
      ],
      data: [],
      loading: false,
      pagination: {
        total: 0
      },
      page: 0,
      rowSelection: {
        type: 'checkbox',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      showSlideFrame: false,
      selectIds: [],
      deleting: false,
      deleteLoading: false
    }
  }

  componentDidMount() {
    this.setState({infoData: this.props.elementDefinition},() => {
      this.getList();
    });
  }

  onSelectChange = (selectedRowKeys) => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    let { selectIds } = this.state;
    if(selected){
      selectIds.filter(item => item.id === record.id).length === 0 && selectIds.push(record);
    }else{
      selectIds.map((item,index) => {
        item.id === record.id && (selectIds[index] = undefined);
      });
      selectIds = selectIds.filter(item => !!item);
    }
    this.setState({selectIds});
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    let { selectIds } = this.state;
    if(selected){
      changeRows.map(item => {
        selectIds.filter(ids => ids.id === item.id).length === 0 && selectIds.push(item);
      })
    }else{
      changeRows.map(item => {
        selectIds.map((ids,index) => {
          if(item.id === ids.id){
            selectIds[index] = undefined;
          }
        });
      });
      selectIds = selectIds.filter(item => !!item);
    }
    this.setState({selectIds});
  };

  getList = () => {
    const { infoData, page } = this.state;
    let temp = {
      sceneElementId: infoData.id,
      page
    };
    this.setState({loading: true});
    interfaceService.getMappingList(temp).then(res => {
      this.setState({
        loading: false,
        data: res.data.rows,
        pagination: {
          total: Number(res.data.total),
          current: page + 1,
          onChange: this.onChangePager,
        }
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  handleAdd = () => {
    this.setState({showSlideFrame: true});
  };

  handleDelete = (e,record) => {
    let ids = [];
    ids.push(record.id);
    this.setState({deleting: true});
    interfaceService.deleteMapping(ids).then(() => {
      this.setState({ deleting: false, page: 0 }, () => {
        this.getList();
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({deleting: false});
    })
  };

  handleBatchDelete = () => {
    const { selectIds, rowSelection } = this.state;
    if(selectIds.length === 0){
      message.error(messages('financial-account.key148')/*请选择再进行删除*/);
      return -1;
    }
    let temp = [], shouldDelete = true;
    selectIds.every(item => {
      if(item.isDefault){
        shouldDelete = false;
        message.error(messages('financial-account.key161')/*预置的无法删除*/);
        return false;
      }
      temp.push(item.id);
      return true;
    });
    if(shouldDelete){
      this.setState({deleteLoading: true});
      interfaceService.deleteMapping(temp).then(() => {
        this.setState({ deleteLoading: false, page: 0 }, () => {
          this.getList();
        });
      }).catch(e => {
        message.error(e.response.data.message);
        this.setState({deleteLoading: false});
      })
    } else {
      rowSelection.selectedRowKeys = [];
      this.setState({selectIds: [], rowSelection})
    }
  };

  isRefresh = (isRefresh) => {
    this.setState({showSlideFrame: false});
    isRefresh === true && this.getList();
  };

  goBack = () => {
    this.context.router.push(menuRoute.getRouteItem('element-definition').url.replace(':tab','accounting-background-definition'));
  };

  render(){
    const { infoList, infoData, columns, data, loading, pagination, rowSelection, showSlideFrame, selectIds } = this.state;
    return(
      <div className="invoice-status">
        <BasicInfo infoList={infoList}
                   infoData={infoData}
                   isHideEditBtn={true}/>
        <div style={{margin:'10px 0px'}}>
          <Button type="primary" onClick={this.handleAdd}>{messages('common.create')}</Button>
          <Button onClick={this.handleBatchDelete} style={{marginLeft:'10px'}} disabled={selectIds.length === 0}>{messages('common.delete')/*删除*/}</Button>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          loading={loading}
          rowKey={'id'}
          rowSelection={rowSelection}
          pagination={pagination}
          bordered
        />
        <SlideFrame show={showSlideFrame}
                    title={messages('financial-account.key102')/*添加映射关系定义*/}
                    params={{
                      showSlideFrame
                    }}
                    content={MappingRule}
                    onClose={(isRefresh) => this.isRefresh(isRefresh)}
                    afterClose={(isRefresh) => this.isRefresh(isRefresh)}/>
        <Affix offsetBottom={0} className="bottom-bar">
          <Button onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>
        </Affix>
      </div>
    )
  }
}

mappingSetting.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {
    elementDefinition: state.financialAccount.elementDefinition
  }
}

export default connect(mapStateToProps)(mappingSetting);
